/**
 * Copyright @2016-present, Sumscope, Inc.
 * All rights reserved.
 */

const logger = require('../../util/logger');
const { isProd } = require('../../util');
const template = require('./template');
const fs = require('fs');
const path = require('path');

let prepareFiles = (path, type, order) => {
  let fileNames = fs.readdirSync(path + '/' + type);
  let prefix = `/${type}/`;
  let pathMap = {};
  fileNames.forEach((name) => {
    let [fileName] = name.split('.');
    pathMap[`/${type}/${fileName}.${type}`] = prefix + name;
  });
  if (typeof order === 'function') {
    return order(pathMap);
  }
  return order.map(key => pathMap[key]);
};

let createHandler = (options) => {
  if (options.autoStatic && isProd()) {
    options.js = prepareFiles(options.release, 'js', options.jsOrder || options.js);
    options.css = prepareFiles(options.release, 'css', options.cssOrder || options.css);
  }
  options = options.process ? options.process(options) : options;
  return async (ctx, next) => {
    let initialState = await options.initState(ctx);
    let opt = options.routeOptions ? options.routeOptions(ctx, options) : options;
    ctx.body = template(opt, initialState);
  };
};

module.exports = function (options, app) {
  options = Object.assign({
    urls: ['/', '/signIn'],
    title: 'ss-koa demo',
    css: ['/css/common.css', '/css/app.css'],
    js: ['/js/common.js', '/js/app.js'],
    initState: () => {}
  }, options);
  if (!options.release && isProd()) {
    throw new Error('Need define release path for spa in production mode.');
  }
  if (!options.initialHtml) {
    options.initialHtml = fs.readFileSync(path.join(__dirname, './loading.html'));
  }
  
  const handler = createHandler(options);
  const router = require('koa-router')();
  options.urls.forEach(uri => router.get(uri, handler));
  app.use(router.routes());
  app.use(router.allowedMethods());
  prepareFiles = null;
  createHandler = null;
};
